package com.hrbu.springboot04.controller;

import com.hrbu.springboot04.bean.User;
import com.hrbu.springboot04.exception.MyException;
import com.hrbu.springboot04.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description:
 * @Author: tanyajun
 * @CreateTime: 2021/4/7
 * @Blog: https://tanyajun.top
 */
@Controller
public class UserController {
    @Autowired
    UserMapper userMapper;
    @GetMapping(value = {"/main","/","/index.html","/index"})
    public String toIndex(){
        return "main";
    }
    @PostMapping("/login")
    public String login(User user, HttpSession session, Model model){
        // 故意抛出自定义异常
        if("admin".equals(user.getUsername())&&"admin".equals(user.getPassword())){
            session.setAttribute("USERSESSION",user);
            return "redirect:/main";
        }
        model.addAttribute("msg","身份验证错误，请重新登录!");
        return "/login";
    }
    @GetMapping(value = {"/login"})
    public String toLoginPage(){
        return "login";
    }

    @GetMapping(value = {"/usertable"})
    public String toUserPage(Model model){
        List<User> userList = userMapper.selectList(null);
        model.addAttribute("userList",userList);
        return "views/usertable";
    }
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Integer id, Model model){
        System.out.println("获取参数: "+id);
        User user = userMapper.selectById(id);
        model.addAttribute("user",user);
        return "views/edit";
    }
    @PostMapping("/edit")
    public String edit(User user){
        System.out.println(user);
        if(user.getId()!=null){
            userMapper.updateById(user);
        }
        return "redirect:/usertable";
    }
    @GetMapping("/del")
    public String del(@RequestParam("id") Integer id){
        System.out.println("获取参数: "+id);
        userMapper.deleteById(id);
        return "redirect:/usertable";
    }
    @PostMapping("/add")
    public String add(User user){
        System.out.println(user);
        int insert = userMapper.insert(user);
        System.out.println(insert==1?"插入成功":"插入失败");
        return "redirect:/usertable";
    }
}
